var fileSearchApp = function (option) {
    this.$url = "fileResolveApp.html";
    this.$window = null;
    this.searchLib={};
}
fileSearchApp.prototype = {
    init: function () {
        this.$window = new Window(2, 1000, 600, "文件检索", {closeCallback: this.destory.bind(this)});
        this.$window.initialize();
        this.$windowContent = $(this.$window.windowContent);
        this.$url = "fileSearchApp.html";
        this.$search_btn = null;
        this.$table = null;
        var _this = this;
        /*加载配置项*/
        $.ajax({
            url: "/loadUserSetting",
            type: 'get',
            data: {},
            cache: false,
            success: function (res) {
                _this.searchLib = res.data;
                $.get(_this.$url, function (r) {
                    jQuery(_this.$windowContent).html(r);
                    _this.init_Reference();
                    _this.create_searchTable();
                    _this.init_tree_content();
                    _this.register_table_evt();
                    _this.jprompt();
                }, "html");

            },
            error: function (res) {
                resResolve(res);
            }
        });

    },
    init_Reference: function () {

        this.$search_btn = this.$windowContent.find(".search_btn");
        this.$search_path = this.$windowContent.find(".file_params");
        this.treefilter = this.$windowContent.find(".filter");
        this.$search_path.tooltip();

    },
    create_searchTable: function () {

        var table = this.$windowContent.find("table").DataTable({
            "lengthMenu": [[5, 6, 50, -1], [5, 10, 50, "All"]],

            ajax: {
                url: "/search",
                data: {
                    keyword: "",
                    path: "",
                    es_from: "",
                    es_size: ""
                }
            },
            scrollY: '50vh',
            scrollCollapse: true,
            "columns": [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                {"data": "name", "className": "name"},
                {"data": "text"},
                {"data": "path"}
            ],
            "order": [[1, 'asc']],
            "language": {
                "lengthMenu": "每页 _MENU_ 条",
                "zeroRecords": "没有查询到任何匹配的结果",
                "info": "当前 _PAGE_ 页共 _PAGES_",
                "infoEmpty": "未找到数据",
                "infoFiltered": "(filtered from _MAX_ total records)",
                "sSearch": "列表内过滤",
                "paginate": {
                    "previous": "上一页",
                    "next": "下一页"
                }
            }, "autoWidth": true
        });
        var _this = this;

        this.$search_btn.click(function () {
            var path = _this.$search_path.val();
            var keyword = _this.$windowContent.find(".keyword").val();
            var es_from = _this.$windowContent.find(".es_from").val();
            var es_size = _this.$windowContent.find(".es_size").val();
            var param = {
                "keyword": keyword,
                "path": path,
                "es_from": es_from,
                "es_size": es_size
            };
            table.settings()[0].ajax.data = param;
            table.ajax.reload();
        });
        this.$windowContent.find(".keyword").keydown(function (event) {
            if (event.keyCode == "13") {
                var path = _this.$search_path.val();
                var keyword = _this.$windowContent.find(".keyword").val();
                var es_from = _this.$windowContent.find(".es_from").val();
                var es_size = _this.$windowContent.find(".es_size").val();
                var param = {
                    "keyword": keyword,
                    "path": path,
                    "es_from": es_from,
                    "es_size": es_size
                };
                table.settings()[0].ajax.data = param;
                table.ajax.reload();
            }

        })
        this.$table = table;
        return table;
    },
    register_table_evt: function () {
        var _this = this;
        this.$windowContent.find("table tbody").on('click', 'td.name', function () {
            var row = _this.$table.row(this.parentElement);
            window.open('/show?rid=' + row.data().rid, '_balnk');
        });

        this.$windowContent.find("table tbody").on('click', 'td.details-control', function (event) {
            var tr = $(this).closest('tr');
            var row = _this.$table.row(tr);
            if (row.child.isShown()) {
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // Open this row
                row.child(_this.hide_line_format(row.data())).show();
                tr.addClass('shown');
            }
            event.stopPropagation();
        });

    },
    hide_line_format: function (d) {
        return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;width: 100%">' +
            '<tr>' +
            '<td>预览内容:</td>' +
            '<td>' + d.content + '</td>' +
            '</tr>' +
            '</table>';
    },
    genNonDuplicateID: function (randomLength) {
        return Number(Math.random().toString().substr(3, randomLength) + new Date().getTime()).toString(36)
    },
    doAjax: function (url, fn) {
        {
            $.ajax({
                url: url,
                type: 'get',
                data: {},
                cache: false,
                success: function (res) {
                    resResolve(res);
                    if (typeof  fn === 'function'&& res.status == "200") {

                        fn();
                    }

                },
                error: function (res) {
                    resResolve(res);
                }
            });
        }
    },
    init_tree_content: function (windowContent) {
        var _this = this;
        this.$windowContent.find(".tree_content .search_tree").remove();
        this.$treeid = this.genNonDuplicateID(3);
        this.$treeidsearch = this.$treeid + "search"
        var tree_content = $("<ul/>").addClass("ztree search_tree").attr("id", this.$treeid);
        this.$windowContent.find(".tree_content").append(tree_content);
        var tree_content_search = $("<ul/>").addClass("ztree search_tree").attr("id", this.$treeidsearch).hide();
        this.$windowContent.find(".tree_content").append(tree_content_search);
        $('div[data-toolbar="toolbar-options"]').toolbar({
            content: '#toolbar-options',
            position: 'left',
        });


        var ztreeOnCheck = function (e, treeId, treeNode) {
            var nodes = _this.$zTreeObj.getCheckedNodes(true),
                v = "",
                rv = "";
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].name + ",";
                rv += nodes[i].id + ",";
            }
            if (v.length > 0) v = v.substring(0, v.length - 1);
            if (rv.length > 0) rv = rv.substring(0, rv.length - 1);
            _this.$search_path.val(rv);
            _this.$search_path.attr("data-original-title", rv);
        };
        var ztreeOnClick = function (e, treeId, treeNode, clickFlag) {

            _this.$zTreeObj.checkNode(treeNode, !treeNode.checked, true);
            _this.$zTreeObj.setting.callback.onCheck();
        };
        var ztreeOnDblClick = function (event, treeId, treeNode) {
            event.stopPropagation();
            if (treeNode && !treeNode.isParent) {
                window.open('/showbypath?path=' + encodeURIComponent(treeNode.id), _this.genNonDuplicateID(3));
            }

        }
        var setFontCss = function (treeId, treeNode) {
            return (treeId.indexOf("search") != -1) ?
                {color: "#A60000", "font-weight": "bold"} :
                {
                    color: "#333", "font-weight": "normal"
                };
        };
        var ztreeOnRightClick = function (event, treeId, treeNode) {
            _this.$zTreeObj.selectNode(treeNode);

            if (treeNode) {

                var menus = [];
                if (!treeNode.isParent) {
                    menus.push({
                        name: "查看", onMenuClick: function () {
                            window.open('/showbypath?path=' + encodeURIComponent(treeNode.id), '_balnk');
                        }
                    });
                    menus.push({
                        name: "刷新文件", onMenuClick: function () {
                            if(_this.searchLib.remoteRepositoryMode!="none"){
                                _this.doAjax('/remoteRepository/update?path=' + encodeURIComponent(treeNode.id), function () {
                                });
                            }else{
                                _this.doAjax('/resolvebypath?path=' + encodeURIComponent(treeNode.id));
                            }
                        }
                    });
                } else {
                    if(_this.searchLib.remoteRepositoryMode!="none"){
                        menus.push({
                            name: "更新远程仓库", onMenuClick: function () {
                                _this.doAjax('/remoteRepository/update?path=' + encodeURIComponent(treeNode.id));
                            }
                        });
                    }
                    if(_this.searchLib.remoteRepositoryMode=="none"){
                        menus.push({
                            name: "添加文件夹", onMenuClick: function () {
                                _this.$windowContent.find(".createFileTitle").text("创建顶级文件夹");
                                _this.$windowContent.find('.createFileMModal').modal('show');
                                _this.$windowContent.find(".createFileSureBut").unbind("click")
                                _this.$windowContent.find(".createFileSureBut").click(function () {
                                    var inputFileName = _this.$windowContent.find(".fileName").val();
                                    if(inputFileName===''||inputFileName===undefined||inputFileName===null){
                                        return false;
                                    }
                                    _this.doAjax('/addfolder?path=' + encodeURIComponent(treeNode.id)+'&folder=' + encodeURIComponent(inputFileName), function () {
                                        _this.$windowContent.find(".fileName").val("");

                                      var newId=  treeNode.id+"/"+inputFileName;
                                      var newNode={
                                          id:newId,
                                          name:inputFileName,
                                          open:false,
                                          isParent:true,
                                          fileCount:0,
                                          parentId:treeNode.id,
                                          dirEmpty:true
                                      }
                                        _this.$zTreeObj.addNodes(treeNode,-1,newNode);

                                        _this.$windowContent.find(".createFileMModal").modal("hide");
                                    });
                                });


                            }
                        });
                        menus.push({
                        name: "添加文件", onMenuClick: function () {
                            new BUpload({
                                src: 'src',
                                upload_url: function () {
                                    return "/upload?path=" + encodeURIComponent(treeNode.id);
                                },
                                list_url: function () {
                                    return "/list?path=" + encodeURIComponent(treeNode.id);
                                },	//图片列表数据获取url
                                ext_allow: "doc|docx|pdf|ppt|txt|xls|xlsx|json|md",
                                ext_refuse: "exe|bat",
                                max_filesize: 1024,
                                max_filenum: 10,
                                callback: function (data) {
                                    if(data){
                                        $(data).each(function (index,ele) {
                                            _this.$zTreeObj.addNodes(treeNode,-1,ele);
                                        })
                                    }
                                }
                            });
                        }
                    });}

                }

                menus.push({
                    name: "拷贝路径", onMenuClick: function () {
                        copyToClipboard(treeNode.id);
                    }
                });
                if (!treeNode.isParent) {
                    menus.push({
                        name: "发送到桌面", onMenuClick: function () {
                            _this.doAjax('/sendToDesktop?path=' + encodeURIComponent(treeNode.id), function () {
                                loadMyDesktop();
                            });
                        }
                    });
                    menus.push({
                        name: "下载文件", onMenuClick: function () {
                            window.open('/downloadFile?path=' + encodeURIComponent(treeNode.id), '_balnk');
                        }
                    });
                }
                $.fn.popupSmallMenu({
                    event: event,
                    menus: menus
                });
            }
        };

        var newNodes = [];
        var setting = {
            check: {
                enable: true,
                chkboxType: {"Y": "", "N": ""},
                chkStyle: "radio",
                radioType: "all"
            },
            view: {
                dblClickExpand: false


            },
            data: {
                key: {
                    children: "sons"
                },
                simpleData: {
                    enable: false,
                    pIdKey: "parentId"
                }
            },
            async: {
                enable: false,
                url: ""
            },
            callback: {
                onCheck: ztreeOnCheck,
                onClick: ztreeOnClick,
                onRightClick: ztreeOnRightClick,
                onDblClick: ztreeOnDblClick,
                onAsyncSuccess: function () {

                }

            }
        };
        var ztreeOnCheckSearch = function (e, treeId, treeNode) {
            var nodes = _this.$zTreeObjsearch.getCheckedNodes(true),
                v = "",
                rv = "";
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].name + ",";
                rv += nodes[i].id + ",";
            }
            if (v.length > 0) v = v.substring(0, v.length - 1);
            if (rv.length > 0) rv = rv.substring(0, rv.length - 1);
            _this.$search_path.val(rv);
            _this.$search_path.attr("data-original-title", rv);
        };
        var ztreeOnClickSearch = function (e, treeId, treeNode, clickFlag) {

            _this.$zTreeObjsearch.checkNode(treeNode, !treeNode.checked, true);
            _this.$zTreeObjsearch.setting.callback.onCheck();
        };
        var ztreeOnDblClickSearch = function (event, treeId, treeNode) {
            event.stopPropagation();
            if (!treeNode.isParent) {
                window.open('/showbypath?path=' + encodeURIComponent(treeNode.id), _this.genNonDuplicateID(3));
            }

        }
        var setFontCssSearch = function (treeId, treeNode) {
            return (treeId.indexOf("search") != -1) ? {color: "#A60000", "font-weight": "bold"} : {
                color: "#333",
                "font-weight": "normal"
            };
        };
        var ztreeOnRightClickSearch = function (event, treeId, treeNode) {
            _this.$zTreeObjsearch.selectNode(treeNode);

            if (treeNode) {

                var menus = [];
                if (!treeNode.isParent) {
                    menus.push({
                        name: "查看", onMenuClick: function () {
                            window.open('/showbypath?path=' + encodeURIComponent(treeNode.id), '_balnk');
                        }
                    });
                    menus.push({
                        name: "刷新文件", onMenuClick: function () {
                            if(_this.searchLib.remoteRepositoryMode!="none"){
                                _this.doAjax('/remoteRepository/update?path=' + encodeURIComponent(treeNode.id), function () {
                                });
                            }else{
                                _this.doAjax('/resolvebypath?path=' + encodeURIComponent(treeNode.id));
                            }

                        }
                    });
                } else if(_this.searchLib.remoteRepositoryMode!="none"){
                    menus.push({
                        name: "更新远程仓库", onMenuClick: function () {
                            _this.doAjax('/remoteRepository/update?path=' + encodeURIComponent(treeNode.id));
                        }
                    });
                }

                menus.push({
                    name: "拷贝路径", onMenuClick: function () {
                        copyToClipboard(treeNode.id);
                    }
                });
                if (!treeNode.isParent) {
                    menus.push({
                        name: "发送到桌面", onMenuClick: function () {
                            _this.doAjax('/sendToDesktop?path=' + encodeURIComponent(treeNode.id), function () {
                                loadMyDesktop();
                            });
                        }
                    });
                    menus.push({
                        name: "下载文件", onMenuClick: function () {
                            window.open('/downloadFile?path=' + encodeURIComponent(treeNode.id), '_balnk');
                        }
                    });
                }
                $.fn.popupSmallMenu({
                    event: event,
                    menus: menus
                });
            }
        }
        var settingSearch = {
            check: {
                enable: true,
                chkboxType: {"Y": "", "N": ""},
                chkStyle: "radio",
                radioType: "all"
            },
            view: {
                dblClickExpand: false,
                fontCss: setFontCssSearch

            },
            data: {

                simpleData: {
                    enable: true,
                    pIdKey: "parentId"
                }
            },
            callback: {
                onCheck: ztreeOnCheckSearch,
                onClick: ztreeOnClickSearch,
                onRightClick: ztreeOnRightClickSearch,
                onDblClick: ztreeOnDblClickSearch,
                onAsyncSuccess: function () {

                }

            }
        };
        $.ajax({
            url: "/readFile2FormatTree",
            type: 'get',
            contentType: "application/x-www-form-urlencoded",
            type: "post",
            dataType: "text",
            cache: false,
            success: function (msg) {
                try {
                    if (!msg || msg.length == 0) {
                        newNodes = [];
                    } else if (typeof msg == "string") {
                        newNodes = eval("(" + msg + ")");
                    } else {
                        newNodes = msg;
                    }
                } catch (err) {
                    newNodes = msg;
                }
                if (newNodes.length === 0) {
                    $.Toast("消息", "请等待系统加载完成", "info", {
                        has_icon: true,
                        has_close_btn: true,
                        fullscreen: false,
                        timeout: 1000,
                        sticky: false,
                        has_progress: true,
                        rtl: false,
                    });
                }
                _this.$zTreeObj = $.fn.zTree.init(_this.$windowContent.find("#" + _this.$treeid), setting, newNodes);
            },
            error: function (res) {

            }
        });

        this.treefilter.keyup(function (event) {
            if (event.keyCode !== 13) {
                return false;
            }
            _this.$doload = false;
            var keyWord = $(this).val().trim();
            /*上一句已经执行了直接清理掉*/
            if (this.searchTime) {
                clearTimeout(this.searchTime);
            }
            this.searchTime = setTimeout(function () {
                if (keyWord === "") {
                    _this.$windowContent.find("#" + _this.$treeid).show();
                    _this.$windowContent.find("#" + _this.$treeidsearch).hide();
                    return;
                }
                ;
                _this.$windowContent.find("#" + _this.$treeid).hide();
                _this.$windowContent.find("#" + _this.$treeidsearch).show();
                var nodeList = _this.$zTreeObj.getNodesByParamFuzzy('name', keyWord, 0);    //通过关键字模糊搜索
                _this.$doload = true;
                _this.lazyLoad(0, nodeList, settingSearch);

            }, 1001);

        });

    },
    lazyLoad: function (index, nodeList, setting) {
        var _this = this;
        var nodelength = nodeList.length;
        if (!this.$doload) {
            return;
        }
        if (index < nodelength) {
            var _list = nodeList.slice(index, index += 100);
            if (index === 100) {
                this.$zTreeObjsearch = $.fn.zTree.init(this.$windowContent.find("#" + this.$treeidsearch), setting, _list);
                this.lazyLoad(index, nodeList);
            } else {
                setTimeout(function () {
                    _this.$zTreeObjsearch.addNodes(null, -1, _list);
                    _this.lazyLoad(index, nodeList);
                }, 1000);
            }
        }
    },
    destory: function () {
        this.$doload = false;
    },
    jprompt: function (title) {
        if(this.searchLib.remoteRepositoryMode!="none"){
            $(".root_add").hide()
            return;
        }
        var _this = this;
        $(".addRootFile").click(function (evt) {
            new BUpload({
                src: 'src',
                upload_url: function () {
                    return "/upload?path="+encodeURIComponent(_this.searchLib.fileSourceDir);
                },
                list_url: function () {
                    return "/list?path=";
                },	//图片列表数据获取url
                ext_allow: "doc|docx|pdf|ppt|txt|xls|xlsx|json|md",
                ext_refuse: "exe|bat",
                max_filesize: 1024,
                max_filenum: 10,
                callback: function (data) {
                    if(data){
                        $(data).each(function (index,ele) {
                            _this.$zTreeObj.addNodes(null,-1,ele);
                        })
                    }
                }
            });
        });
        $(".addRootFolder").click(function (evt) {
            _this.$windowContent.find(".createFileTitle").text("创建顶级文件夹");
            _this.$windowContent.find('.createFileMModal').modal('show');
        });
        _this.$windowContent.find(".createFileSureBut").click(function () {
            _this.$windowContent.find(".createFileMModal").modal("hide");
            var inputFileName = _this.$windowContent.find(".fileName").val();
            if(inputFileName===''||inputFileName===undefined||inputFileName===null){
                return false;
            }
            _this.doAjax('/addfolder?path='+encodeURIComponent(_this.searchLib.fileSourceDir)+'&folder=' + encodeURIComponent(inputFileName), function () {
                _this.$windowContent.find(".fileName").val("");
                var newId=  _this.searchLib.fileSourceDir+"/"+inputFileName;
                var newNode={
                    id:newId,
                    name:inputFileName,
                    open:false,
                    isParent:true,
                    fileCount:0,
                    parentId:_this.searchLib.fileSourceDir,
                    dirEmpty:true
                }
                _this.$zTreeObj.addNodes(null,-1,newNode);

            });

        });
        _this.$windowContent.find(".cancle").click(function () {
            _this.$windowContent.find(".createFileMModal").modal("hide");
            _this.$windowContent.find(".fileName").val("");
        });


    }

}